package com.shanzmoo.db.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.db.sys.entity.RoleEntity;
import com.shanzmoo.db.sys.entity.RoleMenuEntity;
import com.shanzmoo.db.sys.entity.dto.RoleQueryDto;
import com.shanzmoo.db.sys.entity.dto.RoleUpdateDto;
import com.shanzmoo.db.sys.entity.vo.RolePageVo;
import com.shanzmoo.db.sys.entity.vo.RoleSelectVo;
import com.shanzmoo.db.sys.mapper.RoleMapper;
import com.shanzmoo.db.sys.service.IRoleMenuService;
import com.shanzmoo.db.sys.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author Gzhao
 * @since 2020-11-10
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements IRoleService {

    @Autowired
    private IRoleMenuService roleMenuService;

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public SResponse<Boolean> add(RoleEntity roleEntity, List<Integer> menuIds) {
        baseMapper.insert(roleEntity);

        roleMenuService.saveRoleMenuIds(roleEntity.getRoleId(), menuIds);
        return SResponse.ok();
    }

    @Override
    public SResponse<Boolean> deleteById(RoleEntity roleEntity) {

        // todo 校验是否有正常用户还在使用当前角色，如果有则不允许删除角色

        int re = baseMapper.update(
                roleEntity,
                new UpdateWrapper<RoleEntity>()
                        .eq("role_id", roleEntity.getRoleId())
                        .eq("deleted", false)
        );
        if (re > 0) {
            return SResponse.ok();
        }
        return SResponse.fail(Constant.ERRCODE_DATABASE_OPERATION, "角色不存在，删除失败");

    }

    @Override
    public SResponse<Boolean> edit(RoleUpdateDto updateDto) {
        RoleEntity roleEntity = RoleUpdateDto.converted(updateDto);

        int re = baseMapper.update(
                roleEntity,
                new UpdateWrapper<RoleEntity>()
                        .eq("role_id", updateDto.getRoleId())
                        .eq("deleted", false)
        );
        if (re > 0) {
            roleMenuService.saveRoleMenuIds(roleEntity.getRoleId(), updateDto.getMenuIds());
            return SResponse.ok();
        }
        return SResponse.fail(Constant.ERRCODE_DATABASE_OPERATION, "角色不存在，编辑失败");
    }

    @Override
    public SResponse<PageRespBase<RolePageVo>> getPageList(RoleQueryDto queryDto) {
        // 开启分页
        Page page = PageHelper.startPage(queryDto.getPageNum(), queryDto.getPageSize());
        List<RoleEntity> list = baseMapper.selectList(
                new QueryWrapper<RoleEntity>()
                        .like(StrUtil.isNotBlank(queryDto.getRoleName()), "role_name", queryDto.getRoleName())
                        .like(StrUtil.isNotBlank(queryDto.getRoleKey()), "role_key", queryDto.getRoleKey())
                        .eq(ObjectUtil.isNotNull(queryDto.getStatus()), "status", queryDto.getStatus())
                        .eq( "deleted", false)
                        .orderByAsc("role_id")
        );

        List<RolePageVo> reList = list.stream().map(e -> {
            return RolePageVo.create(e);
        }).collect(Collectors.toList());

        PageRespBase<RolePageVo> re = PageRespBase.create(page, reList);
        PageHelper.clearPage();
        return SResponse.ok(re);
    }

    @Override
    public SResponse<List<Integer>> getMenuIdsRoleId(Integer roleId) {
        List<RoleMenuEntity> roleMenuList = roleMenuService.list(new QueryWrapper<RoleMenuEntity>().eq("role_id", roleId));
        if (CollectionUtil.isEmpty(roleMenuList)) {
            return SResponse.ok(Collections.EMPTY_LIST);
        }

        List<Integer> menuIds = roleMenuList.stream().map(RoleMenuEntity::getMenuId).collect(Collectors.toList());
        return SResponse.ok(menuIds);
    }

    @Override
    public List<RoleSelectVo> selectList(Integer outletId) {
        List<RoleEntity> list = baseMapper.selectList(
                new QueryWrapper<RoleEntity>()
                        .eq( "deleted", false)
                        .gt("role_id", 1)
                        .in(ObjectUtil.equal(outletId, 1), "role_id",  3)
                        .in(ObjectUtil.isNotNull(outletId) && outletId > 1, "role_id",  4)
                        .orderByAsc("role_id")
        );
        return list.stream().map(e->{
            return RoleSelectVo.create(e);
        }).collect(Collectors.toList());
    }
}
